import json

def create_game_config(models, template_json, append_number, server_id, DOMAIN, project_id):
    # 目前只历遍三层，所以不建议将端口信息往更深层放，有需要再改吧
    for key1, value1 in template_json.items():
        # 对port字段进行增加
        if "port" in key1: template_json[key1] = template_json[key1] + append_number
        if key1 == "server_id": template_json[key1] = server_id
        if key1 == "domain": template_json[key1] = DOMAIN
        # 判断下层是字典再继续操作
        if isinstance(value1, dict):
            for key2, value2 in value1.items():
                if "port" in key2: template_json[key1][key2] = template_json[key1][key2] + append_number
                if key2 == "server_id": template_json[key1][key2] = server_id
                if key2 == "domain": template_json[key1][key2] = DOMAIN
                if isinstance(value2, dict):
                    for key3, value3 in value2.items():
                        if "port" in key3: template_json[key1][key2][key3] = template_json[key1][key2][
                                                                                 key3] + append_number
                        if key3 == "server_id": template_json[key1][key2][key3] = server_id
                        if key3 == "domain": template_json[key1][key2][key3] = DOMAIN

    # 转换成str进行保存
    config_content = json.dumps(template_json, ensure_ascii=False, sort_keys=True, indent=4)
    # 获取公共分区配置信息进行配置
    cross_setting_str = models.ConfSettingCenter.objects.filter(b_project_id=project_id, purpose=2).first().setting_content
    cross_setting_json = json.loads(cross_setting_str)
    for cross_type, type_content in cross_setting_json.items():
        for cross_server_id, cross_server_content in type_content.items():
            if server_id in cross_server_content["game_server_id"]:
                curr_cross_json = cross_server_content["cross_server_cfg"]
                # 替换变量
                for key, vaule in curr_cross_json.items():
                    config_content = config_content.replace("'${%s}'" % key, "%s" % vaule)
    # 替换server_id
    config_content = config_content.replace("'${server_id}'", "%s" % server_id)

    return config_content
